﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace Mimoza.Transport
{
    public class Packet
    {
        static Packet()
        {
            XmlSerializer ser = new XmlSerializer(typeof(Packet));
        }

        public Packet()
        {
        }

        public Packet(byte[] userSerData)
        {
            m_userObjSerData = userSerData;
        }

        public Packet(TransferObject userData)
        {
            MemoryStream stream = new MemoryStream();
            
            userData.Serialize(stream);

            m_userObjSerData = stream.ToArray();
            m_userObjTypeName = userData.TypeName;
        }

        public string UserDataTypeName
        {
            get
            {
                return m_userObjTypeName;
            }
            set
            {
                m_userObjTypeName = value;
            }
        }

        public byte[] SerializationData
        {
            get
            {
                return m_userObjSerData;
            }
            set
            {
                m_userObjSerData = value;
            }
        }


        public void Serialize(Stream stream)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Packet));

            ser.Serialize(stream, this);
        }

        static public Packet Deserialize(Stream stream)
        {
            XmlSerializer ser = new XmlSerializer(typeof(Packet));

            Packet newPacket = ser.Deserialize(stream) as Packet;
            return newPacket;
        }

        public TransferObject RestoreUserData(TransferObject userDataTemplate)
        {
            if (m_userObjSerData == null) return null;

            MemoryStream stream = new MemoryStream(m_userObjSerData);

            return (userDataTemplate.Deserialize(stream) as TransferObject);
        }

        string m_userObjTypeName = "";
        byte[]  m_userObjSerData = null;
    }
}
